package arrays

import "errors"

type ArrayQueue struct {
	capacity int
	array    []interface{}
	head     int
	tail     int
}

func NewArrayQueue(capacity int) (queue *ArrayQueue) {
	return &ArrayQueue{
		capacity: capacity + 1,
		array:    make([]interface{}, capacity+1),
		head:     0,
		tail:     0,
	}
}

func (queue *ArrayQueue) IsFull() bool {
	return (queue.tail+1)%queue.capacity == queue.head
}

func (queue *ArrayQueue) IsEmpty() bool {
	return queue.tail == queue.head
}

func (queue *ArrayQueue) Size() int {
	return (queue.tail + queue.capacity - queue.head) % queue.capacity
}

func (queue *ArrayQueue) Capacity() int {
	return queue.capacity - 1
}

func (queue *ArrayQueue) Push(e interface{}) (err error) {

	if queue.IsFull() {
		return errors.New("队列已满")
	}

	queue.array[queue.tail] = e
	queue.tail = (queue.tail + 1) % queue.capacity

	return nil
}

func (queue *ArrayQueue) Pop() (e interface{}, err error) {

	if queue.IsEmpty() {
		return nil, errors.New("队列已空")
	}

	e = queue.array[queue.head]
	queue.head = (queue.head + 1) % queue.capacity

	return e, nil
}
